package io.jpress.module.article.service.provider;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import io.jboot.aop.annotation.Bean;
import io.jpress.module.article.service.ArticleVersionService;
import io.jpress.module.article.model.ArticleVersion;
import io.jboot.service.JbootServiceBase;

import java.util.ArrayList;
import java.util.List;

@Bean
public class ArticleVersionServiceProvider extends JbootServiceBase<ArticleVersion> implements ArticleVersionService {

    @Override
    public Object save(ArticleVersion model){
        Object id = super.save(model);

        return id;
    }
    @Override
    public List<ArticleVersion> findAllByPid(int pid) {
        List<Record> records = Db.find("select * from article_version where pid = ? ", pid);
        if (records == null || records.isEmpty()) {
            return null;
        }
        List<ArticleVersion> results= new ArrayList<ArticleVersion>();
        for(Record r:records){
            ArticleVersion a = new ArticleVersion();
            results.add(a.put(r));
        }
        return results;
    }

    @Override
    public boolean checkContent(Integer pid,String content) {
        List<Record> records = Db.find("select * from article_version where pid = ? order by modified desc limit 1", pid);
        if (records == null || records.isEmpty()) {
            return false;
        }
        for(Record r:records){
            ArticleVersion a = new ArticleVersion();
            a.put(r);
            if(a.getContent().contentEquals(content))return true;
        }
        return false;
    }

    @Override
    public boolean checkNewByPid(long pid) {
        boolean flag = false;
        List<Record> records = Db.find("select * from article_version where pid = ? ", pid);
        try{
        if (records == null || records.isEmpty()) {
            throw new Exception("query DB failed, no result can be processed~! //by fuye");
        }}catch (Exception e){
            e.printStackTrace();
        }
      if(records.size()>1){
          flag = false;
      } else if(records.size()==1){
          flag = true;
      }
        return flag;
    }

    @Override
    public Long getTheLastVersionByPid(Long pid) {
        Long flag = 0L;
        List<Record> records = Db.find("select * from article_version where pid = ? order by modified desc limit 1", pid);
        try{
            if (records == null || records.isEmpty()) {
                throw new Exception("query DB failed, no result can be processed~! //by fuye");
            }}catch (Exception e){
            e.printStackTrace();
        }
        for(Record r :records){
            ArticleVersion tmp = new ArticleVersion();
            tmp.put(r);
            flag = tmp.getId();
        }

        return flag;
    }
}